package com.wtx.fitness.controller;

import com.wtx.fitness.common.Result;
import com.wtx.fitness.common.ResultCode;
import com.wtx.fitness.exception.BusinessException;
import com.wtx.fitness.exception.UnauthorizedException;
import com.wtx.fitness.mapper.AdminMapper;
import com.wtx.fitness.mapper.StudentMapper;
import com.wtx.fitness.util.TokenUtil;
import com.wtx.fitness.util.OSSUtil;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@RestController
@RequestMapping("/api/upload")
public class UploadController {

  @Autowired
  private OSSUtil ossUtil;

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private AdminMapper adminMapper;

  /**
   * 上传头像
   * 
   * @param file    头像文件
   * @param request HTTP请求
   * @return 上传结果，包含头像URL
   */
  @PostMapping("/avatar")
  public Result<Map<String, String>> uploadAvatar(
      @RequestParam("file") MultipartFile file,
      HttpServletRequest request) {

    // 检查文件是否为空
    if (file.isEmpty()) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "上传文件不能为空");
    }

    // 检查文件类型
    String contentType = file.getContentType();
    if (contentType == null || !contentType.startsWith("image/")) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "只能上传图片文件");
    }

    // 检查文件大小（限制为2MB）
    if (file.getSize() > 2 * 1024 * 1024) {
      throw new BusinessException(ResultCode.PARAM_ERROR, "图片大小不能超过2MB");
    }

    // 从Token工具类获取用户信息
    String userType = TokenUtil.getUserType();
    String userId = TokenUtil.getUserId();

    if (userType == null || userId == null) {
      throw new UnauthorizedException("请先登录");
    }

    try {
      // 上传头像到OSS
      String avatarUrl = ossUtil.uploadAvatar(file, userType, userId);

      // 更新数据库中的头像URL
      if ("student".equals(userType)) {
        studentMapper.updateAvatar(userId, avatarUrl);
      } else if ("admin".equals(userType)) {
        adminMapper.updateAvatar(Integer.valueOf(userId), avatarUrl);
      }

      // 返回结果
      Map<String, String> data = new HashMap<>();
      data.put("url", avatarUrl);

      return Result.success(data);
    } catch (IOException e) {
      throw new BusinessException(ResultCode.SYSTEM_ERROR, "文件上传失败: " + e.getMessage());
    }
  }
}